package jmine.tec.web.tags;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import jmine.tec.web.servlet.util.WebSpringHelper;

import org.apache.commons.lang.StringUtils;

/**
 * Tag de breadCrumb.
 */
public class BreadCrumbTag extends BodyTagSupport {
    private static final String WIKILINK_PREFIX_PARAMETER = "jmine.tec.wikilink.prefix";

    public static final String REQUEST_KEY = "BreadCrumb";

    private String suffix;

    private String helpText;

    /**
     * @return the helpText
     */
    public String getHelpText() {
        return this.helpText;
    }

    /**
     * @param helpText the helpText to set
     */
    public void setHelpText(String helpText) {
        this.helpText = helpText;
    }

    /**
     * @return sufixo.
     */
    public String getSuffix() {
        return this.suffix;
    }

    /**
     * Define sufixo.
     * 
     * @param suffix sufixo.
     */
    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    /**
     * Imprime breadCrumbs.
     * 
     * @throws JspException caso algo de inesperado ocorra.
     * @return super.doEndTag()
     */
    @Override
    public int doEndTag() throws JspException {
        String contextPath = ((HttpServletRequest) this.pageContext.getRequest()).getContextPath();
        BodyContent bodyContent = this.getBodyContent();
        String content;
        if (bodyContent != null) {
            content = bodyContent.getString();
        } else {
            content = this.pageContext.getRequest().getParameter(REQUEST_KEY);
        }
        if (StringUtils.isNotBlank(content)) {
            String path = this.suffix == null ? content : content + ':' + this.suffix;
            List<String> pathComponents = Arrays.asList(path.split(":"));

            String wikiLink = this.createWikiLink(pathComponents);
            String breadCrumbPrefix = StringUtils.join(pathComponents.subList(0, pathComponents.size() - 1), " | ") + " | ";
            String breadCrumbSuffix = pathComponents.get(pathComponents.size() - 1);

            StringBuilder html = new StringBuilder();
            html.append("<input type=\"hidden\" name=\"").append(REQUEST_KEY).append("\" value=\"").append(content).append("\" />");
            html.append("<div style=\"width:98%;margin:0 auto\">");
            html.append("<span class=\"tdMainTitle\">");
            html.append("<img src=\"").append(contextPath).append("/images/icon_title.gif\"> ");
            html.append(breadCrumbPrefix);
            html.append("<strong>").append(breadCrumbSuffix).append("</strong>");
            if (this.helpText != null && !"".equals(this.helpText)) {
                if (wikiLink == null) {
                    html.append("<a href='#' onclick='return false' class='helpText'>");
                } else {
                    html.append("<a href='").append(wikiLink).append("' target=\"_blank\" class=\"helpText\">");
                }
                html.append("<img src='").append(contextPath).append("/images/help.gif' class='helpTextImg' />");
                html.append("<span>").append(this.helpText).append("</span>");
                html.append("</a>");
            }
            html.append("</span>");
            html.append("<span class=\"tdMainTitle\" colspan=\"2\"><hr class=\"hrMainTitle\"></span></div>");

            try {
                this.pageContext.getOut().write(html.toString());
            } catch (IOException e) {
                throw new JspException(e);
            }
        }

        return super.doEndTag();
    }

    /**
     * Cria a URL de link para a wiki correspondente à página, caso o prefixo tenha sido fornecido pelo contexto de servlets.
     * 
     * @param pathComponents pathComponents
     * @return url
     */
    private String createWikiLink(List<String> pathComponents) {
        if (this.pageContext.getServletContext().getInitParameter(WIKILINK_PREFIX_PARAMETER) != null) {
            String prefix = WebSpringHelper.getBean(this.pageContext, WIKILINK_PREFIX_PARAMETER, String.class);
            if (StringUtils.isBlank(prefix)) {
                return null;
            }
            return prefix + StringUtils.join(pathComponents, " ").replaceAll("/", "-");
        } else {
            return null;
        }
    }
}
